﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using FB2er.Properties;
using FB2er.View;
using FB2er.ViewModel;
using Microsoft.Win32;

namespace FB2er
{
    public partial class MainWindow
    {
        private readonly string _startFileName;
        private bool _isInFullScreen;

        public MainWindow(string startFileName)
        {
            _startFileName = startFileName;
            InitializeComponent();
            DataContext = new MainVM(fdr);
            Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ((MainVM) DataContext).LoadSettings();
            if (!string.IsNullOrEmpty(_startFileName))
                LoadBook(_startFileName, Settings.Default.LastPageNumber);
        }

        private void DocDragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.All;
            e.Handled = true;
        }

        private void DocDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var droppedFilePaths =
                  e.Data.GetData(DataFormats.FileDrop, true) as string[];

                if (droppedFilePaths != null && droppedFilePaths.Length > 0)
                    LoadBook(droppedFilePaths[0], 0);
            }
        }

        private void ExecuteOpen(object sender, ExecutedRoutedEventArgs e)
        {
            var fo = new OpenFileDialog { Filter = "FB2 books (*.zip)|*.zip|All files (*.*)|*.*" };
            if ((bool)fo.ShowDialog())
                LoadBook(fo.FileName, 0);
        }

        private void ExecuteOpenRecent(object sender, ExecutedRoutedEventArgs e)
        {
            LoadBook((string)((MenuItem)e.OriginalSource).Header, 0);
        }

        private void ExecuteAbout(object sender, ExecutedRoutedEventArgs e)
        {
            var about = new About { Owner = this };
            about.ShowDialog();
        }

        private void ExecuteFullScreen(object sender, ExecutedRoutedEventArgs e)
        {
            if (_isInFullScreen)
            {
                WindowStyle = WindowStyle.SingleBorderWindow;
                WindowState = WindowState.Normal;
                Topmost = false;
            }
            else
            {
                WindowStyle = WindowStyle.None;
                WindowState = WindowState.Maximized;
                Topmost = true;
            }
            _isInFullScreen = !_isInFullScreen;
        }

        private void LoadBook(string fileName, int pageNumber)
        {
            ((MainVM)DataContext).LoadBook(fileName, pageNumber);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ((MainVM) DataContext).SaveSettings();
        }
    }
}
